<template>
  <div class="app-container">
    <div class="filter-container">
        <el-row :gutter="20">
            <el-col :span="4">
                <el-input v-model="listQuery.tradeNo" placeholder="订单编号"></el-input>
            </el-col>

            <el-col :span="3">
                <el-select v-model="listQuery.paid" placeholder="支付状态" clearable class="filter-item">
                    <el-option v-for="(item, key) in payStatusList" :key="key" :label="item" :value="key" />
                </el-select>
            </el-col>

            <el-col :span="3">
                <el-select v-model="listQuery.status" placeholder="订单状态" clearable class="filter-item">
                    <el-option v-for="(item, key) in statusList" :key="key" :label="item" :value="key" />
                </el-select>
            </el-col>

            <el-col :span="3">
                <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">查询</el-button>
            </el-col>
        </el-row>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column label="ID" width="80" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="100px" label="订单编号" align="center">
        <template slot-scope="{row}">
          <span>{{ row.orderId }}</span>
        </template>
      </el-table-column>
 
      <el-table-column min-width="60px" label="订单金额/元" align="center">
        <template slot-scope="{row}">
          <span>{{ row.totalPrice }}</span>
        </template>
      </el-table-column> / 

      <el-table-column min-width="80px" label="支付金额/元" align="center">
        <template slot-scope="{row}">
          <span v-if="row.payType">{{ row.payPrice }} / {{ row.payType }}</span>
        </template>
      </el-table-column>

      <el-table-column min-width="60px" label="订单状态" align="center">
        <template slot-scope="{row}">
          <span v-if="row.status != 0 || row.paid == 1">{{ statusList[row.status] }}</span>
          <span v-if="row.paid == 0">待付款</span>
        </template>
      </el-table-column>      

      <el-table-column width="200px" align="center" label="下单时间">
        <template slot-scope="scope">
          <span>{{ scope.row.addTime | parseTimeFormat('YYYY-MM-DD HH:mm:ss') }}</span>
        </template>
      </el-table-column>

      <el-table-column align="left" label="操作" max-width="200">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="showDetail(scope.row.id)">详细</el-button>
          <el-button v-if="scope.row.status == 0 && scope.row.paid == 0" type="primary" size="mini" @click="makeCollections(scope.row.id, scope.row.orderId)">收款</el-button>
          <el-button v-if="scope.row.status == 0 && scope.row.paid == 1" type="primary" size="mini" @click="deliveryGoodsDialog(scope.row.id, scope.row.orderId)">发货</el-button>
          <el-button v-if="scope.row.status == 1 && scope.row.paid == 1" type="primary" size="mini" @click="receiving(scope.row.id, scope.row.orderId)">收获</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 订单详细弹层 -->
    <el-dialog title="订单详细" :visible.sync="orderDetail.dialog.visible" top="2vh" :center="true" :width="orderDetail.dialog.dialogContainerWidth">
        <order-detail v-bind:orderInfo="orderDetail.info" v-bind:statusList="statusList" v-bind:payStatusList="payStatusList"></order-detail>
    </el-dialog>

    <!-- 订单发货弹层 -->
    <el-dialog title="订单发货" :visible.sync="orderDelivery.dialog.visible" top="2vh" :center="true" :width="orderDelivery.dialog.dialogContainerWidth">
        <el-form :model="orderDelivery.form" :rules="orderDelivery.rules" ref="deliveryRuleForm">
            <el-form-item label="订单编号" :label-width="orderDelivery.formLabelWidth">
                {{ orderDelivery.orderSn }}
            </el-form-item>
            <el-form-item label="快递公司" :label-width="orderDelivery.formLabelWidth" prop="id">
                <el-select v-model="orderDelivery.form.id" placeholder="请选择快递公司">
                    <el-option v-for="(company, key) in orderDelivery.companyList" :key="key" :label="company.name" :value="company.id"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="运单编号" :label-width="orderDelivery.formLabelWidth" prop="code">
                <el-input v-model="orderDelivery.form.code" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="orderDelivery.dialog.visible = false">取 消</el-button>
            <el-button type="primary" @click="deliveryGoods">确认发货</el-button>
        </div>
    </el-dialog>

    <pagination
      v-show="total>0"
      :total="total"
      :current-page.sync="listQuery.pageNo"
      :limit.sync="listQuery.pageSize"
      @pagination="changePage"
    />

  </div>
</template>

<script>
import { findOrder, orderDelivery, orderPayment, orderChangeStatus, orderChangePrice } from "@/api/order";
import { deliveryList } from "@/api/delivery";
import waves from "@/directive/waves"; // waves directive
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination

import OrderDetail from "@/components/Shop/OrderDetail"

export default {
  name: "OrderList",
  components: { OrderDetail, Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: "success",
        draft: "info",
        deleted: "danger"
      };
      return statusMap[status];
    }
  },
  data() {
    return {
      statusList: {'-3': '已退款', '-2': '退货成功', '-1': '申请退款', '0': '待发货', '1': '待收货' , '2': '已收货', '3': '待评价'},
      payStatusList: {'0': '未支付', '1': '已支付'},
      list: null,
      orderDetail: {
        dialog: {
          dialogLabelWidth: '120px',
          dialogContainerWidth: '80%',
          visible: false,
        },
        info: {}
      },
      orderDelivery: {
        form: {
            id: '',
            code: '',
            orderId: '',
        },
        rules: {
            id: [{required: true, message: "请选择快递公司", trigger: "change"}],
            code: [{required: true, message: "请输入运单编号", trigger: "blur"}],
        },
        companyList: {},
        dialog: {
          dialogLabelWidth: "120px",
          dialogContainerWidth: "50%",
          visible: false,
        },
        formLabelWidth: '120px',
        orderSn: '',
      },
      total: 0,
      listLoading: true,
      listQuery: {
        tradeNo: '',
        status: null,
        paid: null,
        pageNo: 0,
        pageSize: 10,
        pageType: "P"
      }
    };
  },
  created() {
    this.getList();
    this.deliveryList();
  },
  methods: {
    // 获取订单列表
    getList() {
      this.listLoading = true;
      findOrder(this.listQuery).then(response => {
        this.list = response.data;
        this.total = response.count;
        this.listLoading = false;

        console.log('list', this.list);
      });
    },
    // 获取订单详细
    showDetail(id) {
      this.orderDetail.dialog.visible = true
      
      for (let i in this.list) {
        if (this.list[i].id == id) {
          this.orderDetail.info = this.list[i];
        }
      }
    },
    // 获取快递公司
    deliveryList() {
      deliveryList({pageNo: 0, pageSize: 50, pageType: 'A'}).then(response => {
        this.orderDelivery.companyList = response.data;
        console.log('companyList', this.orderDelivery.companyList);
      });
    },
    // 订单收款
    makeCollections(id, orderSn) {
        this.$confirm('确认订单' + orderSn + '已付款？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            orderPayment({
                orderId: id,
                paid: 1,
                payType: 'administrators'
            }).then(response => {
                if (response.success == true) {
                    this.getList();
                }
            });
        });
        
    },
    // 订单发货
    deliveryGoodsDialog(id, orderId) {
        this.orderDelivery.dialog.visible = true;
        this.orderDelivery.orderSn = orderId;
        this.orderDelivery.form.orderId = id;
    },
    // 确认发货
    deliveryGoods() {
        let that = this;
        this.$refs['deliveryRuleForm'].validate(async valid => {
            if (valid === true) {
                this.$confirm('确认'+ that.orderDelivery.orderSn +'单要发货?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.orderDelivery.dialog.visible = false;
                    let tempCompanyList = that.orderDelivery.companyList;
                    let data = {
                        id: this.orderDelivery.form.orderId,
                        deliveryId: this.orderDelivery.form.id,
                        deliveryName: '',
                        deliveryCode: '',
                    };

                    for (let p in tempCompanyList) {
                        console.log(tempCompanyList[p]);
                        if (tempCompanyList[p].id == data.deliveryId) {
                            data.deliveryName = tempCompanyList[p].name;
                            data.deliveryCode = tempCompanyList[p].code;
                            break ;
                        }
                    }

                    orderDelivery(data).then(res => {
                        if (res.success == true) {
                            this.$notify({
                                title: "发货成功",
                                message: "订单发货成功",
                                type: "success",
                                duration: 2000
                            });
                            that.getList();
                        }
                    });
                }).catch(() => {
                    return false;      
                });
            } 
        });
    },
    // 收货
    receiving(id, orderSn) {
        let that = this;
        this.$confirm('确认' + orderSn + '订单收货?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            orderChangeStatus({id: id, status: 2}).then(res => {
                if (res.success == true) {
                    this.$notify({
                        title: "收货成功",
                        message: "订单收货成功",
                        type: "success",
                        duration: 2000
                    });
                    that.getList();
                }
            });
        });
    },
    handleFilter() {
      this.listQuery.pageNo = 0;
      this.getList();
    },
    // 分页
    changePage(value) {
      this.listQuery.pageNo = value.page - 1;
      this.listQuery.pageSize = value.limit;
      this.getList();
    },
    // 页码或者当前页发生变化
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.listQuery.pageNo = val - 1;
      this.getList();
    },
  }
};
</script>

<style scoped>
.edit-input {
  padding-right: 100px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
  
}
label{font-weight: normal !important ;}
</style>
